<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="类型名称" prop="typeName">
              <el-input v-model="queryParams.typeName" placeholder="请输入类型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['shopping:type:add']" type="primary" icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['shopping:type:edit']" type="success" icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['shopping:type:remove']" type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['shopping:type:export']" type="warning" icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="类型名称" align="center" prop="typeName" />
        <el-table-column label="状态" align="center" prop="state">
          <template #default="scope">
            <div>
              <el-tag v-if="scope.row.state === 0" style="cursor: pointer" :type="''">可用</el-tag>
              <el-tag v-else style="cursor: pointer" :type="'info'">不可用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="顺序排序" align="center" prop="sort" />
        <el-table-column label="链接" align="center" prop="linkUrl" />
        <el-table-column label="是否显示" align="center" prop="isShow">
          <template #default="scope">
            <div>
              <el-tag v-if="scope.row.isShow === 0" style="cursor: pointer" :type="''">不显示</el-tag>
              <el-tag v-else style="cursor: pointer" effect="dark">显示</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="绑定规格" placement="top">
              <el-button v-hasPermi="['shopping:type:edit']" link type="primary" icon="Tools" @click="handleRelation(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['shopping:type:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['shopping:type:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="typeFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="图标" prop="imgUrl">
          <single-pic v-model="form.imgPath" type="image" :upload-type="2" :num="1" :width="120" :height="120" @handle-checked="chooseImg" />
        </el-form-item>
        <el-form-item label="排序索引" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入顺序排序" />
        </el-form-item>
        <el-form-item label="前端路由" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入前端路由" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio :value="0" :label="0">正常</el-radio>
            <el-radio :value="1" :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="小程序显示" prop="isShow">
          <el-radio-group v-model="form.isShow">
            <el-radio :value="1" :label="1">显示</el-radio>
            <el-radio :value="0" :label="0">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改商品规则值(规格)对话框 -->
    <el-dialog v-model="dialogRelation.visible" :title="dialogRelation.title" width="750px" append-to-body>
      <div style="height: 100%">
        <el-transfer
          v-model="valueRuleIds"
          style="height: 100%"
          filterable
          :titles="['未绑定规格', '已绑定规格']"
          filter-placeholder="请输入规格名称"
          :props="{
            key: 'ruleId',
            label: 'ruleName'
          }"
          :data="allRuleList"
          @change="changeItem"
        >
        </el-transfer>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Type" lang="ts">
import { listType, getType, delType, addType, updateType } from '@/api/shopping/product/type';
import { listRuleRelation, getRuleRelation, delRuleRelation, addRuleRelation, updateRuleRelation, removeByRuleId, getTransferData } from '@/api/shopping/product/ruleRelation';
import { TypeVO, TypeQuery, TypeForm } from '@/api/shopping/product/type/types';

import SinglePic from '@/components/SingleMaterial/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const typeList = ref<TypeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const allRuleList = ref([]);
const valueRuleIds = ref([]);

const queryFormRef = ref<ElFormInstance>();
const typeFormRef = ref<ElFormInstance>();

const queryParamsRelation = ref({
  cateId: undefined,
  cateChildId: undefined,
  cateChildName: undefined
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogRelation = reactive<DialogOption>({
  visible: false,
  title: ''
});

const formRelation = ref({
  id: undefined,
  ruleId: undefined,
  ruleName: undefined,
  cateId: undefined,
  cateChildId: undefined,
  cateChildName: undefined
});

const initFormData: TypeForm = {
  id: undefined,
  typeName: undefined,
  parentId: undefined,
  state: undefined,
  imgUrl: undefined,
  sort: undefined,
  linkUrl: undefined,
  isShow: undefined,
  imgPath: undefined
};

const data = reactive<PageData<TypeForm, TypeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    typeName: undefined,
    parentId: undefined,
    state: undefined,
    imgUrl: undefined,
    sort: undefined,
    linkUrl: undefined,
    isShow: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    typeName: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '父类型id不能为空', trigger: 'blur' }],
    state: [{ required: true, message: '状态 0 - 不可用 1 - 可用不能为空', trigger: 'blur' }],
    linkLogo: [{ required: true, message: '种类的图片标识地址不能为空', trigger: 'blur' }],
    sort: [{ required: true, message: '顺序排序不能为空', trigger: 'blur' }],
    linkUrl: [{ required: true, message: '当前类型的 可跳转小程序的链接不能为空', trigger: 'blur' }],
    isShow: [{ required: true, message: '是否显示 0 - 不显示 1 - 显示不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品分类列表 */
const getList = async () => {
  loading.value = true;
  const res = await listType(queryParams.value);
  typeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/**
 *  选择图片
 * @param data
 */
const chooseImg = (data) => {
  console.log('product type chooseImg', data);
  if (data.length > 0) {
    this.form.imgPath = data[0].imgUrl;
    this.form.imgUrl = data[0].url;
  }
};

/**
 *  关联配置
 * @param row
 */
const handleRelation = (row) => {
  resetRelation();
  dialogRelation.title = '规格绑定';
  dialogRelation.visible = true;
  if (row.parentId > 0) {
    queryParamsRelation.value.cateId = row.parentId;
    queryParamsRelation.value.cateChildId = row.id;
  } else {
    queryParamsRelation.value.cateId = row.id;
  }
  queryParamsRelation.value.cateChildName = row.typeName;

  getTransferData(queryParamsRelation).then((response) => {
    valueRuleIds.value = response.data.valueRuleIds;
    allRuleList.value = response.data.allRuleList;
  });
};

const changeItem = async (value, direction, movedKeys) => {
  console.log('changeItem value', value);
  console.log('changeItem direction', direction);
  console.log('changeItem movedKeys', movedKeys);

  if (direction == 'right') {
    //添加
    formRelation.value.ruleId = movedKeys[0];
  } else {
    formRelation.value.ruleId = movedKeys[0];
  }

  formRelation.value.cateId = queryParamsRelation.value.cateId;
  formRelation.value.cateChildId = queryParamsRelation.value.cateChildId;
  formRelation.value.cateChildName = queryParamsRelation.value.cateChildName;

  if (direction == 'right') {
    //添加
    await addRuleRelation(formRelation.value)
      .then((response) => {
        proxy?.$modal.msgSuccess('新增成功');
      })
      .finally(() => {});
  } else {
    //删除
    await removeByRuleId(formRelation.value);
    proxy?.$modal.msgSuccess('删除成功');
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  typeFormRef.value?.resetFields();
};

/** 表单重置 */
const resetRelation = () => {
  formRelation.value = {
    id: undefined,
    ruleId: undefined,
    ruleName: undefined,
    cateId: undefined,
    cateChildId: undefined,
    cateChildName: undefined
  };
  // typeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TypeVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加商品分类';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TypeVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getType(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改商品分类';
};

/** 提交按钮 */
const submitForm = () => {
  typeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateType(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addType(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TypeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商品分类编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delType(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'shopping/type/export',
    {
      ...queryParams.value
    },
    `type_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
